<template>
  <a-card :bordered="false">
    <search :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <!-- table区域-begin -->
    <div class="page_table">
      <vxe-grid
        ref="xGrid"
        :border="true"
        :resizable="true"
        :showOverflow="true"
        size="mini"
        :loading="loading"
        :height="pageHeight-seachHeight-90"
        :align="left"
        :columns="columns"
        :data="dataSource"
        :toolbar-config="tableToolbar"
        v-bind="vexConfig"
        @radio-change='radioChangeEvent'
        :radio-config="{ trigger: 'row'}"
      >
        <template #toolbar_buttons>
          <div class="table-operator">
            <a-button type="primary" v-has="'TerminalApproval:approval'" :disabled="selectionRows.length!=1||[3,4].includes(selectionRows[0].approvalStatus)"
                      @click="handleEdit(selectionRows[0])">审批
            </a-button>
            <a-button type="primary" @click="downExportXls('cnTerminalApproval_service')">导出</a-button>
          </div>
        </template>

        <template #avatarslot="{ row }">
          <viewer :images="[row.avatar]">
            <a-avatar shape="square" size="small" :src="row.avatar" icon="user"/>
          </viewer>
        </template>
        <template #status="{ row,rowIndex }">
          <a-switch :checked="row.status" size="small" @change="handleStatus(row,$event)"/>
        </template>
        <template #detail="{ row,rowIndex }">
          <a @click="handleDetail(row)">{{ row.terminalCode }}</a>
        </template>

        <template #action="{ row:record }">
          <!--          <a v-has="'terminal:approval'" @click='handleEdit()'>审批</a>-->
          <!--          <a-divider type='vertical' />-->
          <a href="javascript:" @click='handleBusiness("门店审批",record)'>日志</a>
        </template>

        <template #pager>
          <vxe-pager :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
                     :currentPage.sync="ipagination.current" :page-size.sync="ipagination.pageSize"
                     :total="ipagination.total"
                     :pageSizes="ipagination.pageSizeOptions" @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <terminal-approval-modal ref="modalForm" @ok="modalFormOk"></terminal-approval-modal>
    <terminal-approval-up-modal ref="modalFormUp" @ok="modalFormOk"></terminal-approval-up-modal>
    <WhiteModal modal-width="90%" ref="WhiteModal" @ok="handelSaveWhite"></WhiteModal>

    <config-pos-cust ref="ConfigPosCust" @ok="savePosCust"></config-pos-cust>
    <business-log ref="businessLog"></business-log>

  </a-card>
</template>

<script>
import WhiteModal from './modules/WhiteModal'
import { postAction, getFileAccessHttpUrl, getAction } from '@/api/manage'
import TerminalApprovalModal from './modules/TerminalApprovalModal'
import TerminalApprovalUpModal from './modules/TerminalApprovalUpModal'
import uploadExcel from '@/components/upload-file/UploadExcel.vue'
import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import ConfigPosCust from './modules/TerPosCustConfigModal'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'terminal-list',
  mixins: [PageListMixin],
  components: {
    uploadExcel,
    TerminalApprovalModal,
    WhiteModal,
    ConfigPosCust,
    TerminalApprovalUpModal
  },
  data() {

    return {
      tokenHeader1: { 'Authorization': 'Bearer ' + Vue.ls.get(ACCESS_TOKEN).access_token },
      description: '门店审批列表',
      searchConfig: [{
        type: 'input',
        name: 'terminalCode',
        placeholder: '门店编码'
      },
        {
          type: 'input',
          name: 'terminalName',
          placeholder: '门店名称'
        },
        {
          type: 'a-select',
          name: 'businessFlag',
          placeholder: '类型',
          option:[
            {
              name:'门店新增',
              value:'门店新增'
            },
            {
              name:'门店修改',
              value:'门店修改'
            },
            {
              name:'门店升级',
              value:'门店升级'
            }
          ]
        },
        {
          type: 'j-select',
          dictCode:'bpm_status',
          name: 'approvalStatus',
          placeholder: '审批状态'
        },
        {
          type: 'input',
          name: 'createName',
          placeholder: '创建人'
        },
        {
          type: 'input',
          name: 'businessLicense',
          placeholder: '营业执照'
        },
        {
          type: 'date-range', //范围选择
          range: ['startDate', 'endDate'],
          name: 'range',
          format: 'YYYY-MM-DD',
          placeholder: ['开始时间', '结束时间']
        }
      ],
      //字典数组缓存
      sexDictOptions: [],
      //列定义
      columns: [{
        type: 'radio',
        minWidth: 60,
        width: 60,
        fixed: 'left'
      },
        {
          title: '门店编码',
          field: 'terminalCode',
          minWidth: 100,
          fixed: 'left',
          slots: { default: 'detail' }
        },
        {
          title: '门店名称',
          minWidth: 80,
          field: 'terminalName'
        },
        {
          title: '营业执照',
          minWidth: 80,
          field: 'businessLicense'
        },
        {
          title: '类型',
          minWidth: 80,
          field: 'businessFlag'
        },
        {
          title: '门店等级',
          minWidth: 80,
          field: 'terminalLevel_dictText'
        },
        {
          title: '所属组织',
          minWidth: 80,
          field: 'orgName'
        },
        {
          title: '客户名称',
          minWidth: 80,
          field: 'custName'
        },
        {
          title: '省',
          minWidth: 80,
          field: 'province'
        },
        {
          title: '市',
          minWidth: 80,
          field: 'city'
        },
        {
          title: '区',
          minWidth: 80,
          field: 'area'
        },
        {
          title: '详细地址',
          minWidth: 80,
          field: 'address'
        },
        {
          title: '创建人',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          minWidth: 80,
          field: 'createTime'
        },
        {
          title: '审批流程',
          align: 'left',
          field: 'currentNodeDesc',
          fixed: 'right',
          minWidth: 120
        },
        {
          title: '审批状态',
          align: 'left',
          field: 'approvalStatusStr',
          width: 80,
          fixed: 'right',
          minWidth: 80
        },
        // {
        //   title: '操作',
        //   fixed: 'right',
        //   minWidth: 120,
        //   width: 120,
        //   field: 'action',
        //   slots: {
        //     default: 'action'
        //   }
        // }
      ],
      isorter: {
        permflag: 'termianl_approval_page_impl'
      },
      url: {
        list: window._CONFIG['domianURL'] + '/approval/cnTerminalApproval/findPageList',
        delete: window._CONFIG['domianURL'] + '/approval/cnTerminalApproval/delete',
        detail: window._CONFIG['domianURL'] + '/approval/cnTerminalApproval/getInfo',
        // detail: window._CONFIG['domianURL'] + '/cnTerminalController/getCnTerminalByIdOrTerminalCode',
        deleteBatch: '/approval/cnTerminalApproval/deleteBatch',
        exportXlsUrl: window._CONFIG['domianURL'] + '/approval/cnTerminalApproval/exportXls',
        approval: window._CONFIG['domianURL'] + '/approval/cnTerminalApproval/saveOrUpdate',

      },
      currentWhite: {}
    }
  },

  computed: {
    importExcelUrl: function () {
      return `${this.url.importExcelUrl}`
    }
  },

  methods: {
    handleDetail: async function (record) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id, terminalCode: record.terminalCode })
        if (res.success) {
          if (res.result) {
            record = res.result
            console.log(record)
          }
        } else {
          this.$message.error(res.message)
        }
      }
      if (record.businessFlag == '门店升级') {
        this.$refs.modalFormUp.title = '详情'
        this.$refs.modalFormUp.disableSubmit = true
        this.$refs.modalFormUp.edit(record)
        return
      }
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.edit(record)
    },
    // async approval() {
    //   if (!this.url.approval) {
    //     this.$message.error('请设置url.autogen属性!')
    //     return
    //   }
    //   if (this.url.detail) {
    //     const res = await getAction(this.url.detail, { id: record.id, terminalCode: record.terminalCode })
    //     if (res.success) {
    //       if (res.result) {
    //         record = res.result
    //         console.log(record)
    //       }
    //     } else {
    //       this.$message.error(res.message)
    //     }
    //   }
    //   this.$refs.modalForm.title = '详情'
    //   this.$refs.modalForm.disableSubmit = true
    //   this.$refs.modalForm.edit(record)
    // },
    handleEdit: async function (record) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id, terminalCode: record.terminalCode })
        if (res.success) {
          if (res.result) {
            record = res.result
            console.log(record)
          }
        } else {
          this.$message.error(res.message)
        }
      }
      if (record.businessFlag == '门店升级') {
        this.$refs.modalFormUp.title = '审批'
        this.$refs.modalFormUp.disableSubmit = true
        this.$refs.modalFormUp.edit(record)
        return
      }
      this.$refs.modalForm.title = '审批'
      this.$refs.modalForm.disableSubmit = true
      this.selectionRows = []
      this.$refs.modalForm.edit(record)
    },

    handleConfigTer(record, type, modal = 'ConfigPosCust') {
      this.$refs[modal].showModal(record)
      return false
    },

    async handleWhite(record) {
      this.currentWhite = record
      this.$refs.WhiteModal.showModal(record.terminalCode)
    },
    savePosCust(params) {
      postAction(this.url.savePosCust, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigPosCust.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigPosCust.confirmLoading = false
        //that.close();
      })
    },
    handelSaveWhite(typeList, productList, positionList, record) {
      let that = this
      const tList = typeList.map(type => Object.assign({
        code: type.code,
        name: type.name,
        dataType: 3
      }))
      const pList = productList.map(type => Object.assign({
        code: type.code,
        name: type.name,
        remarks: type.imgUrl,
        dataType: 4
      }))
      const positions = positionList.map(type => Object.assign({
        code: type.positionCode,
        name: type.positionName,
        dataType: 5
      }))
      if (!record.extendVos) record.extendVos = []
      const retainRows = record.extendVos.filter(row => [1, 2].includes(Number(row.dataType)))
      record.extendVos = [...retainRows, ...tList, ...pList, ...positions]
      that.loadData()
      postAction(window._CONFIG['domianURL'] + '/cnTerminalController/saveTerExtend', record).then(async (res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.$refs.WhiteModal.showModal('')
          this.$refs.WhiteModal.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.WhiteModal.confirmLoading = false
        //that.close();
      })
    },
    async handleStock(record) {
      const modal = this.$refs.stockModalForm
      modal.edit(record)
      modal.title = '详情'
      modal.disableSubmit = true
      return true
    },
    postAction,
    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    initDictConfig() {
      console.log('--我才是真的方法!--')
      //初始化字典 - 性别
      initDictOptions('sex').then((res) => {
        if (res.success) {
          this.sexDictOptions = res.result
        }
      })
    },
    //跳转单据页面
    jump() {
      this.$notification.success('跳转 ： jump')
    },
    onBirthdayChange: function (value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.birthday_begin = dateString[0]
      this.queryParam.birthday_end = dateString[1]
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.field == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.field)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.field)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (colSettings.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    // 编辑

    // 上传

    handleUploadFile: function () {
      this.$refs.uploadFile.add()
      // this.$refs.uploadFile.title = "上传";
      this.$refs.uploadFile.disableSubmit = false
    }
  },
  created() {
    this.initColumns()
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
